package com.razorthink.shell.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class NativeCommandExecutor {
	public static String execute(String cmd) throws IOException,
			InterruptedException {
		long timeNow = System.currentTimeMillis();
		Process p = Runtime.getRuntime().exec(cmd);
		// p.waitFor();
		InputStreamReader is = new InputStreamReader(p.getInputStream());
		BufferedReader reader = new BufferedReader(is);
		String line = "", result = "";
		while ((line = reader.readLine()) != null) {
			result += line + "\n";
		}
		is.close();
		p.destroy();
		result += "Time taken: " + (System.currentTimeMillis() - timeNow)
				/ 1000 + " seconds.";
		return stripServerAddress(result);
	}

	/**
	 * Removes the server address from fabric execution response string. <br/>
	 * <b> Example: </b><br/>
	 * This is a sample response as a result of fabric execution. <br/>
	 * <i> [ubuntu@ec2-23-23-12-64.compute-1.amazonaws.com] Executing task
	 * 'upload' <br/>
	 * [ubuntu@ec2-23-23-12-64.compute-1.amazonaws.com] put:
	 * /home/rzt/deploy/instance/webapp/www_dev.war ->
	 * /home/ubuntu/sshtemp/www_dev.war <br/>
	 * [ubuntu@ec2-23-23-12-64.compute-1.amazonaws.com] sudo: find
	 * /home/ubuntu/sshtemp -type f -print0 | xargs -0 chmod 777 <br/>
	 * [ubuntu@ec2-23-23-12-64.compute-1.amazonaws.com] out: rm: cannot remove
	 * `/home/ubuntu/sshtemp/www_dev.war': No such file or directory <br/>
	 * [ubuntu@ec2-23-23-12-64.compute-1.amazonaws.com] out: <br/>
	 * <br/>
	 * </i> This method strips off <br/>
	 * '[ubuntu@ec2-23-23-12-64.compute-1.amazonaws.com]' from each line and
	 * returns the text.
	 * 
	 * @param dirtyText
	 * @return
	 */
	public static String stripServerAddress(String dirtyText) {
		// Pattern p = Pattern.compile(pattern);
		// Matcher m = p.matcher(dirtyText);
		// while (m.find()) {
		// m.replaceAll("");
		// }
		return dirtyText.replaceAll("\r", "\n")
				.replaceAll("\\[.*@[^\\]]*\\]\\s", "")
				.replaceAll("^Exe[^']*'[^']*'", "").replaceAll("out: ", "")
				.replaceAll("run: ", "").replaceAll("Done.", "")
				.replaceAll("\nDisconnecting from[^\n]*\n", "").trim()
				.replaceAll("\n{2,}", "\n");
	}
	// public static String executeInCmdPrompt(String cmd) throws IOException,
	// InterruptedException {
	// return execute("cmd.exe /c " + cmd);
	// }
}
